package com.xxx.common.web.handler;


import com.xxx.common.web.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Map<String, String> businessException(BusinessException e) {
        Map<String, String> map = new HashMap<>();
        map.put("code", e.getCode());
        map.put("message", e.getMessage());
        map.put("stackTraceMsg", StringUtils.substring(ExceptionUtils.getStackTrace(e), 0, 500));
        log.warn(e.getMessage(), e);
        return map;
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Map<String, String> exception(Exception e) {
        Map<String, String> map = new HashMap<>();
        map.put("code", "500");
        map.put("message", e.getMessage());
        map.put("stackTraceMsg", StringUtils.substring(ExceptionUtils.getStackTrace(e), 0, 500));
        log.error(e.getMessage(), e);
        return map;
    }

}